import docker

from ai.utils.config import docker_volume_path
# 模型测试
from docker.errors import APIError

def check_container():
    try:
        client = docker.from_env()
        container = client.containers.get("modelpredict")
        if container:
            return True
        else:
            return False
    except APIError as e:
        print(f"Failed to get container list: {e}")
        return False

def stop_container():
    try:
        client = docker.from_env()
        container = client.containers.get("modelpredict")
        if container:
            container.stop()
    except APIError as e:
        print(f"Failed to stop container: {e}")

def create_container():
    try:
        client = docker.from_env()
        container = client.containers.run('ainew:latest',
                                                name="modelpredict",
                                                ports={"8088": "8088"},
                                                volumes={docker_volume_path: {'bind': '/usr/src/app', 'mode': 'rw'}},
                                                detach=True, remove=True, tty=True,
                                                command='python app.py')
        if container:
            return True
        else:
            return False
    except APIError as e:
        print(f"Failed to create container: {e}")
        return False

# 判断是否需要开启容器
# def check_container():
#     client = docker.from_env()
#     for container in client.containers.list():
#         if container.name == "modelpredict":
#             return True
#     return False
#
#
# # 关闭容器
# def stop_container():
#     client = docker.from_env()
#     for container in client.containers.list():
#         if container.name == "modelpredict":
#             container.stop()
#
#
# # 开启容器
# def create_container():
#     client = docker.from_env()
#     container = client.containers.run('ainew:latest',
#                                       name="modelpredict",
#                                       ports={"8088": "8088"},
#                                       volumes={docker_volume_path: {'bind': '/usr/src/app', 'mode': 'rw'}},
#                                       detach=True, remove=True, tty=True,
#                                       command='python app.py')
